/**
 * 工具函数
 */
import store from '@/store' 
import {ApiupLoadFiles,upLoadOrigin} from '../api'
import {isPreview} from "./test"
//设置cookie
export const setCookie = (name,value,Days) => {
    var exp = new Date();
    exp.setTime(exp.getTime() + Days*24*60*60*1000);
    document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();
}

export const getCookie = (key) =>{
    var arr,reg = RegExp('(^| )'+key+'=([^;]+)(;|$)');
    if (document.cookie.match(reg)) {
        arr = document.cookie.match(reg)
        return decodeURIComponent(arr[2]);
    }    
    else {
        return null;
    }
}


export const delCookie = (key) => {
    // 删除cookie
    var date = new Date();
    date.setTime(date.getTime() - 1);
    var delValue = getCookie(key);
    if (delValue != null) {
        document.cookie = key+'='+delValue+';expires='+date.toGMTString();
    }
}

//防抖
export const debounce = (func,wait,immediate) => {
    let timeout;
    return function () {
        let context = this;
        let args = arguments;

        if (timeout) clearTimeout(timeout);
        if (immediate) {
            var callNow = !timeout;
            timeout = setTimeout(() => {
                timeout = null;
            }, wait)
            if (callNow) func.apply(context, args)
        }
        else {
            timeout = setTimeout(function(){
                func.apply(context, args)
            }, wait);
        }
    }
}

//节流
export const throttle = (func, wait) => {
    let previous = 0;
    return function() {
        let now = Date.now();
        let context = this;
        let args = arguments;
        if (now - previous > wait) {
            func.apply(context, args);
            previous = now;
        }
    }
}

const roleCard = (data) => {
    const obj = {
        1: '管理员',
        2: '科主任',
        3: '科研人员'
    }
    const id = store.state.userInfo.role_id
    if(Array.isArray(data)){
        return data.includes(obj[id])
    }else{
        return data === obj[id]
    }
}

export const adminShow = roleCard.bind(null,'管理员')
export const personnelShow = roleCard.bind(null,'科研人员')


const chnNumChar = {
    1:"一",
    2:"二",
    3:"三",
    4:"四"
}
export const utils_conversion = (key) => {
    return chnNumChar[key]
}

export const objToStr = (obj = {},Symbol="、")=>{
    return Object.values(obj).join(Symbol)
}

export const utils_upload = (url,name) => {
    ApiupLoadFiles(url).then(res => {
        const link = URL.createObjectURL(res)
        if(isPreview(name)){
            const win = window.open(link,name,'toolbar=no,location=no,status=no')
            setTimeout(function(){
                win.document.title = name
                URL.revokeObjectURL(link)
            },500);
        }else{
            let a = document.createElement("a")
            a.href = link
            a.download = name
            a.click()
            URL.revokeObjectURL(link)
        }
        
    })
    
}